<?php

require_once 'Login.php';
require_once 'Module.php';
require_once 'SiteEdit.php';
require_once 'Kanedo/Translate.php';
require_once 'Kanedo/Language.php';
require_once 'Kanedo/Controller/Abstract.php';
class moduleController extends Kanedo_Controller_Abstract 
{
	/**
	 * @var Login
	 */
	protected $login;
	
	/**
	 * 
	 * @var Module
	 */
	protected $module;
	
	/**
	 * User object
	 *
	 * @var Login
	 */
	protected $_user;
	public function init()
	{
		/**
		 * Alle Controller des Adminmoduls muessen das haben:
		 */
		$this->login = new Login(Kanedo_Registry::getInstance()->db);
		try {
			if(!$this->login->isLoggedIn())
			{
				header("Location:http://".$_SERVER['HTTP_HOST'].$this->_request->getBaseUrl()."admin/login");
			}
		}catch(Kanedo_Db_Exception $e) {
			header("Location:http://".$_SERVER['HTTP_HOST'].$this->_request->getBaseUrl()."admin/login");
			
		}
		$this->_user = $this->login->getCurrentUser();
		
		$this->module = new Module(Kanedo_Registry::getInstance()->db);
		$this->_view->page = new ArrayObject();
		$this->_view->page['title'] = "Module Verwalten";
		$this->_view->page['css'] = '<link href="/CSS/admin/style-edit.css" rel="stylesheet" type="text/css" media="all" /><link href="/CSS/admin/jquery.wysiwyg.css" rel="stylesheet" type="text/css" media="all" />';
		$this->_view->page['javascript'] = 	'<script type="text/javascript" src="/JS/interface.js"></script>'.
											'<script type="text/javascript" src="/JS/jquery.event.drag.js"></script>'.
											'<script type="text/javascript" src="/JS/help.js"></script>'.
											'<script type="text/javascript" src="/JS/headline_rotate.js"></script>';
		$this->_view->user = $this->_user;
		
	}
	public function indexAction()
	{
		$this->_view->count_modules = count($this->module->getAllRegisteredModules());
		$list = $this->module->getAllNonRegisteredModules();
		$this->_view->UnRegisteredModuleList = "<ul>";
		foreach($list as $var)
		{
			$this->_view->UnRegisteredModuleList .="<li>".$var."</li>";
		}
		$this->_view->UnRegisteredModuleList .= "</ul>";
		if(empty($list)) {
			$this->_view->UnRegisteredModuleList = "Keine Module zum installieren vorhanden!";
		}
		$this->_view->registeredModuleList = "<ul>";
		$list = $this->module->getAllRegisteredModules();
		for($i=0; $i<count($list); $i++)
		{
			$this->_view->registeredModuleList .="<li>".$list[$i]['name']."</li>";
		}
		$this->_view->registeredModuleList .= "</ul>";
		if(count($list)<1)
		{
			$this->_view->registeredModuleList = "Keine Module installiert!";
		}
		$list = $this->module->getAllRegisteredModules();

	}
	
	public function addAction()
	{
		if($this->_request->getGetParam('message'))
		{
			$lang = new Kanedo_Language();
			$user = $this->login->getCurrentUser();
			$lang->changeLanguage($user['lang']);
			$translate = new Kanedo_Translate("ini", $lang);
			$translate->configure('./lang/admin/messages_admin.ini');
			$this->_view->info = $translate->_($this->_request->getGetParam('message'));
		}
		$this->_view->UnRegisteredModuleList = false;
		if($this->_request->getPostParam('upload'))
		{			
			if($_FILES['module']['type'] != "application/zip")
			{
				throw new Exception('no_zip');
			}else {
				$destination = $_SERVER['DOCUMENT_ROOT']."/tmp/".$_FILES['module']['name'];
				if(move_uploaded_file($_FILES['module']['tmp_name'], $destination))
				{
					$zip = new ZipArchive();
					$res = $zip->open($destination);
					if ($res === TRUE) {
					    $zip->extractTo($_SERVER['DOCUMENT_ROOT']."/MODULES/");
					    $zip->close();
					    header("Location: /admin/module/add?action=install&message=upload_successfull");
					} else {
				  	 throw new Exception('cant_open_zip');
					}

				}else {
					throw new Exception("cant_move_uploaded_file");
				}
			}
		}
		if($this->_request->getGetParam('action') && $this->_request->getGetParam('action') == 'install')
		{
			$list = $this->module->getAllNonRegisteredModules();
			$this->_view->UnRegisteredModuleList = "<ul>";
			foreach($list as $var)
			{
				$this->_view->UnRegisteredModuleList .="<li>".$var."</li>";
			}
			$this->_view->UnRegisteredModuleList .= "</ul>";
			if(empty($list)) {
				$this->_view->UnRegisteredModuleList = "Keine Module zum installieren vorhanden!";
			}
		}
		
		if($this->_request->getGetParam('name'))
		try {
			$this->module->addModuleToLibrary($this->_request->getGetParam('name'));
			header("Location: /admin/module/add?action=install&message=install_successfull");
		}catch(Kanedo_Db_Exception $e)
		{
			$msg = $e->getMessage();		
			$pattern = '#(.*){(.*)}#sx';
			preg_match_all($pattern, $msg, $result);
			$lang = new Kanedo_Language();
			$user = $this->login->getCurrentUser();
			$lang->changeLanguage($user['lang']);
			$translate = new Kanedo_Translate("ini", $lang);
			$translate->configure('./translate.ini');
			$msg = trim($result[1][0]);
			$this->_view->error .= $translate->_($msg);
			$this->_view->error .= $e->getMessage();
			
		}catch(Kanedo_Model_Exception $e)
		{
			$lang = new Kanedo_Language();
			$user = $this->login->getCurrentUser();
			$lang->changeLanguage($user['lang']);
			$translate = new Kanedo_Translate("ini", $lang);
			$translate->configure('./translate.ini');
			$this->_view->error .= $translate->_($e->getMessage());
		}
	}
	
	public function deleteAction($id = false)
	{
		if($this->_request->getGetParam('name') )
		$this->module->remove($this->_request->getGetParam('name'), true);
		if($id)
		$this->module->remove($id, true);
	}
	
	public function getmoduleAction()
	{
		$m_id = substr($this->_request->getGetParam('id'), 2, strlen($this->_request->getGetParam('id')));
		if($m_id)
		{

			try {
				$module = $this->module->getModuleById($m_id);
				include $module[0]['path']."/Outputfile.php";
				$moduleObject = new Outputfile();
				$moduleObject->init($this->_request, $this->_view, 1);
				$moduleConfig = new Kanedo_Config_Ini($module[0]['configfile']);
				$a_module_json = array(
									   "/MODULES/".$module[0]['name']."/".$moduleConfig->$module[0]['name']->css,
									   $moduleConfig->$module[0]['name']->js,
									   $moduleObject->getConfigureUI()
									  );
				$module_json = json_encode($a_module_json);
				$this->_view->content = $module_json;
			}catch(Exception $e)
			{
				/**
				 * @todo Exceptionhandling
				 */
				echo $e->getMessage();
			}
		}
	}
	
	public function manageAction()
	{
		$this->_view->page['javascript'] .= '<script type="text/javascript" src="/JS/manage_module.js"></script>';
		if($this->_request->getGetParam('message'))
		{
			$lang = new Kanedo_Language();
			$user = $this->login->getCurrentUser();
			$lang->changeLanguage($user['lang']);
			$translate = new Kanedo_Translate("ini", $lang);
			$translate->configure('./lang/admin/messages_admin.ini');
			$this->_view->info = $translate->_($this->_request->getGetParam('message'));
		}
		$this->_view->moduleList = "";
		$modules = $this->module->getAllRegisteredModules();
		for($i=0; $i<count($modules); $i++)
		{
			$this->_view->moduleList .= '<tr>
											<td><input type="checkbox" name="module[][id]" value="'.$modules[$i]['id_model_registered'].'" class="delete"/></td>
											<td>'.$modules[$i]['name'].'</td>
											<td><input type="image" name="delete[id]" value="'.$modules[$i]['id_model_registered'].'" src="/IMAGES/admin/button_cancel.png" /></td>
										</tr>';
		}
		if($this->_request->getPostParam('deleteAll'))
		{
			if(!$this->_request->getPostParam('module'))
			{
				throw new Kanedo_Front_Controller_Exception('no_module_choosen');
			}
			$moduleDelete = $this->_request->getPostParam('module');
			for($i=0; $i<count($moduleDelete); $i++)
			{
				$name = $this->deleteAction($moduleDelete[$i]['id']);
			}
			header("Location:/admin/module/manage?message=delete_successfull");
		}elseif($this->_request->getPostParam('delete'))
		{
			if(!$this->_request->getPostParam('delete'))
			{
				throw new Kanedo_Front_Controller_Exception('no_module_choosen');
			}
			$moduleDelete = $this->_request->getPostParam('delete');
			$this->deleteAction($moduleDelete['id']);
			header("Location:/admin/module/manage?message=delete_successfull");
		}
	}
	
	
}